package com.ljx.security.aspect;

import com.ljx.security.exception.PermissionException;
import com.ljx.security.util.WebUtils;
import com.ljx.security.annotation.HasPermission;
import com.ljx.utils.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/2/24 10:55
 * @Version 1.0
 */
@Aspect
@Component
public class PermissionAspect {
	@Pointcut(value = "@annotation(com.ljx.security.annotation.HasPermission)")
	public void pointcut(){}

	@Around("pointcut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		// 获取方法对象
		MethodSignature methodSignature= (MethodSignature) joinPoint.getSignature();
		Method method = methodSignature.getMethod();
		// 获取方法上的HasPermission
		HasPermission annotation = method.getAnnotation(HasPermission.class);
		if (annotation!=null){
			// 获取注解上的value值
			String permission = annotation.value();
			//在springmvc任意唯一获取request对象。
			// 请求对象获取后我们可以根据请求获取请求信息中头中的token，然后就可以查找到该用户是否有该权限
			HttpServletRequest request = WebUtils.getRequest();
			String token = request.getHeader("token");
			//解析token
			Map<String, Object> map = JwtUtil.getTokenChaim(token);
			List<String> authorities = (List<String>) map.get("authorities");
			if(!authorities.contains(permission)){
				// 自定义异常信息(手写异常类)，需要写全局异常 来处理这个异常,
				throw new PermissionException("权限不足");
			}
		}
		return joinPoint.proceed();
	}
}
